﻿using MediatR;
using Microsoft.AspNetCore.Mvc;
using Order.Api.Read.Application.Command;
using Order.Api.Read.Dto.Order;
using Order.ErrorCode;
using Order.Domain.OrderDomain;
using System;
using System.Threading.Tasks;

namespace Order.Api.Read.Controllers
{
    /// <summary>
    /// 退款控制器
    /// 提供退款相关的API接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class RefundController : ControllerBase
    {
        private readonly IMediator _mediator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者模式处理器</param>
        public RefundController(IMediator mediator)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator), "中介者处理器不能为空");
        }

        /// <summary>
        /// 获取退款分页数据
        /// 支持关键字搜索和时间范围筛选
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetRefundPage([FromQuery] RefundQueryDto query)
        {
            try
            {
                // 构建查询命令
                var command = new RefundPageCommand
                {
                    Query = query ?? new RefundQueryDto()
                };

                // 发送命令并获取结果
                var result = await _mediator.Send(command);

                return Ok(result);
            }
            catch (ArgumentException ex)
            {
                // 参数错误
                return BadRequest(new { message = ex.Message });
            }
            catch (Exception ex)
            {
                // 记录异常日志
                // TODO: 添加日志记录
                return StatusCode(500, new { message = "获取退款分页数据时发生错误" });
            }
        }

        /// <summary>
        /// 获取退款详情
        /// 根据退款ID查询详细信息，包括关联的订单和患者信息
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetRefundDetail(int id)
        {
            try
            {
                // 参数验证
                if (id <= 0)
                {
                    return BadRequest(new { message = "退款ID必须大于0" });
                }

                // 构建查询命令
                var command = new RefundDetailCommand { Id = id };

                // 发送命令并获取结果
                var result = await _mediator.Send(command);

                // 检查是否找到记录
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的退款记录" });
                }

                return Ok(result);
            }
            catch (ArgumentException ex)
            {
                // 参数错误
                return BadRequest(new { message = ex.Message });
            }
            catch (Exception ex)
            {
                // 记录异常日志
                // TODO: 添加日志记录
                return StatusCode(500, new { message = "获取退款详情时发生错误" });
            }
        }
    }
}
